//
//  JWTUpdateUserInfoViewController.m
//  JWT
//
//  Created by ndm on 17/1/20.
//  Copyright © 2017年 com.jwtsoft. All rights reserved.
//

#import "JWTUpdateUserInfoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "JWTUpdateNameViewController.h"
#import "JWTUserDetailCell.h"
#import "JWTUpdateSignatureViewController.h"
#import "JWTChangePWDViewController.h"

@interface JWTUpdateUserInfoViewController()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) NSArray *hintSec0Array;

@property (nonatomic,strong) NSArray *hintSec1Array;

@property (nonatomic,strong) UITableView *tableView;

@end

static  NSString *JWTUpdateInfoCell_Identifier = @"JWTUpdateInfoCell_Identifier";

@implementation JWTUpdateUserInfoViewController
SHARED_INSTANCE_IMPLEMENTATION(JWTUpdateUserInfoViewController);
-(instancetype)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _hintSec0Array = @[@"头像",@"姓名",@"性别"];
    _hintSec1Array = @[@"修改密码",@"个性签名"];
    
    [self initWithTableView];
    
    //修改成功后，回调刷新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh_updateUserInfoAction:) name:@"refresh_updateUserInfoAction" object:nil];
    
};

-(void) refresh_updateUserInfoAction:(NSNotification *) notice{
    [_tableView reloadData];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void) initWithTableView{
    if (_tableView == nil) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,UISCREEN_WIDTH , UISCREEN_HEIGHT-getNAVI_TOP_HEIGHT()-Cell_Margin)];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.backgroundColor = RGB_LightGrayBackGround;
        [self.view addSubview:tableView];
        [tableView registerClass:[JWTUserDetailCell class] forCellReuseIdentifier:JWTUpdateInfoCell_Identifier];
        _tableView = tableView;
    }
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return _hintSec0Array.count;
    }else if(section == 1){
        return _hintSec1Array.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JWTUserDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:JWTUpdateInfoCell_Identifier forIndexPath:indexPath];
    cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
  
    [self updateCellWithJWTUserDetailCell:cell AndIndexPath:indexPath];
    return cell;
}

-(CGFloat) updateCellWithJWTUserDetailCell:(JWTUserDetailCell *)cell AndIndexPath:(NSIndexPath *)indexPath{
    cell.iconImageView.hidden = YES;
    cell.contentLabel.hidden = NO;
    cell.frame = CGRectMake(cell.left, cell.top, cell.width, cell.contentLabel.bottom+Cell_Margin);
    if (indexPath.section == 0) {
        cell.hintNameLabel.text = [_hintSec0Array objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {//头像
            cell.iconImageView.hidden = NO;
            cell.contentLabel.hidden = YES;
            cell.frame = CGRectMake(cell.left, cell.top, cell.width, cell.iconImageView.bottom+Cell_Margin);
            cell.hintNameLabel.center = CGPointMake(cell.hintNameLabel.center.x, cell.height*0.5);
            
            [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:APPDELEGATE.userInfo.icon] placeholderImage:[UIImage imageNamed:@"DefaultHead"]];
        }else if (indexPath.row == 1){//姓名
            if ([APPDELEGATE.userInfo.name isEqualToString:@""]) {
                cell.contentLabel.text = @"未设置";
            }else{
                cell.contentLabel.text = APPDELEGATE.userInfo.name;
            }
        }else if (indexPath.row == 2){//性别
            if ([APPDELEGATE.userInfo.gender isEqualToString:@"0"]) {
                cell.contentLabel.text = @"男";
            }else if ([APPDELEGATE.userInfo.gender isEqualToString:@"1"]){
                cell.contentLabel.text = @"女";
            }else{
                cell.contentLabel.text = @"未设置";
            }
        }
    }else if (indexPath.section == 1){
        cell.hintNameLabel.text = [_hintSec1Array objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {
            
        }else if (indexPath.row == 1) {
            cell.contentLabel.text = APPDELEGATE.userInfo.signature;
        }
    }
    return cell.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            UIActionSheet *updUserIcon = [[UIActionSheet alloc] initWithTitle:@"修改头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从本地相册选择",@"拍照", nil];
            updUserIcon.tag = 0;
            [updUserIcon showInView:self.view];
        }else if (indexPath.row == 1) {
            JWTUpdateNameViewController *vc = [[JWTUpdateNameViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 2) {
            UIActionSheet *sexSelSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
            sexSelSheet.tag = 1;
            [sexSelSheet showInView:self.view];
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            JWTChangePWDViewController *vc = [[JWTChangePWDViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 1){
            JWTUpdateSignatureViewController *vc = [[JWTUpdateSignatureViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

/**
 UIActionSheet 代理事件
 */
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 0) {
            if (buttonIndex == 1) {
                UIImagePickerController* imagePicker = [[UIImagePickerController alloc] init];
                imagePicker.delegate = self;
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                
#if 0
                //只照相
                imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
#endif
                
                [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
                if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
                {
                    //判断相机是否能够使用
                    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
                    if(status == AVAuthorizationStatusAuthorized) {
                        // authorized
                        [self presentViewController:imagePicker animated:YES completion:NULL];
                    } else if(status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied){
                        // restricted
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [[[UIAlertView alloc] initWithTitle:@"无法使用相机" message:@"请在“设置-隐私-相机”选项中允许访问你的相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
                        });
                    } else if(status == AVAuthorizationStatusNotDetermined){
                        // not determined
                        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                            if(granted){
                                [self presentViewController:imagePicker animated:YES completion:NULL];
                            } else {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [[[UIAlertView alloc] initWithTitle:@"无法使用相机" message:@"请在“设置-隐私-相机”选项中允许访问你的相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
                                });
                            }
                        }];
                    }
                }
            }else if (buttonIndex == 0){
                /**打开本地相册*/
                UIImagePickerController *ipc = [[UIImagePickerController alloc]init];//设置实例化对象
                ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//表明当前图片的来源为相册
                ipc.delegate = self;//设置代理
                ipc.allowsEditing = YES;//设置用户对图片是否可编辑
                [self presentViewController:ipc animated:YES completion:nil];
            }
    }else if (actionSheet.tag == 1) {
        if (buttonIndex == 0) {
            //设置为男
            APPDELEGATE.userInfo.gender = @"0";
        }else if(buttonIndex == 1){
            //设置为女
            APPDELEGATE.userInfo.gender = @"1";
        }else{
            return;
        }
        //
        [self updateUserSex];
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSLog(@"%@",info);
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        NSData *data = nil;
        NSString *extSting; // = [info objectForKey:@"UIImagePickerControllerReferenceURL"];
        if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
            UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
            [picker dismissViewControllerAnimated:YES completion:nil];
            extSting = [JWTCommons saveToDocument:image];
        }else if(picker.sourceType == UIImagePickerControllerSourceTypeCamera){
            //        if (extSting == nil) {
            UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
            [picker dismissViewControllerAnimated:YES completion:nil];
            extSting = [JWTCommons saveToDocument:orgImage];
        }
        
        NSLog(@"%@",extSting);
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:extSting forKey:@"name"];
        if (data != nil) {
            [dict setObject:data forKey:@"data"];
        }else{
            [dict setObject:UIImageJPEGRepresentation(info[UIImagePickerControllerOriginalImage],0.5) forKey:@"data"];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
        NSData *base64Data = [dict objectForKey:@"data"];
        [self updateUserIconWithIconBase64String:[base64Data base64EncodedStringWithOptions:(NSDataBase64Encoding64CharacterLineLength)]];
        NSLog(@"%@",[base64Data base64EncodedStringWithOptions:(NSDataBase64Encoding64CharacterLineLength)]);
    }
}

/**
 修改用户头像
 */
-(void) updateUserIconWithIconBase64String:(NSString *) base64String{
    [HUD showUIBlockingIndicator];
    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] updateUserIconWithActionUpdateUserIcon];
    NSDictionary *dict = @{@"userid":APPDELEGATE.userInfo.userid,@"icon":[NSString stringWithFormat:@"data:image/jpg;base64,%@",base64String] ,@"tokenid":APPDELEGATE.userInfo.tokenid};
    [AFNHttpsRequest requestWithUrl:urlString WithParam:dict WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
        [HUD hideUIBlockingIndicator];
        NSLog(@"%@",model);
        if (model) {
            [HUD showToast:[model objectForKey:@"message"]];
            if ([[model objectForKey:@"code"] integerValue] == 200) {
                APPDELEGATE.userInfo.icon = [[model objectForKey:@"data"] objectForKey:@"url"];
                [_tableView reloadData];
            }
        }
    }];
}

/**
  修改用户性别
 */
-(void) updateUserSex{
    NSString *urlString = [[JWTAPPHttpsUrl sharedInstance] updateUserSexWithActionUpdateSex];
    [HUD showUIBlockingIndicator];
    NSDictionary *dict = @{@"userid":APPDELEGATE.userInfo.userid,@"sex":APPDELEGATE.userInfo.gender,@"tokenid":APPDELEGATE.userInfo.tokenid};
    [AFNHttpsRequest requestWithUrl:urlString WithParam:dict WithGetDataDidFinishBlock:^(id model, NSURLSessionDataTask *task, NSError *error) {
        [HUD hideUIBlockingIndicator];
        if (model) {
            if ([[model objectForKey:@"code"] integerValue] == 200) {
                [HUD showToast:[model objectForKey:@"message"]];
                if ([APPDELEGATE.userInfo.gender integerValue]== UserSexMale) {
                    [[JWTUserHeaderView sharedInstance].userSexImageView setImage:[UIImage imageNamed:@"my_gender_male"]];
                }else{
                    [[JWTUserHeaderView sharedInstance].userSexImageView setImage:[UIImage imageNamed:@"my_gender_female"]];
                }
                [_tableView reloadData];
            }else{
                [HUD showToast:[model objectForKey:@"message"]];
            }
        }
    }];
}


///
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static JWTUserDetailCell *cell = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cell = [tableView dequeueReusableCellWithIdentifier:JWTUpdateInfoCell_Identifier];
    });
    return [self updateCellWithJWTUserDetailCell:cell AndIndexPath:indexPath];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.05;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 0.05)];
    footerView.backgroundColor = RGB_LightGrayBackGround;
    return footerView;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 10)];
    headerView.backgroundColor = RGB_LightGrayBackGround;
    return headerView;
}



@end
